package com.probiz.estore.product.dao.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.probiz.estore.Constants;
import com.probiz.estore.catalog.dao.ProductCategoryDao;
import com.probiz.estore.catalog.dao.VirtualCategoryDao;
import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.common.model.catalog.VirtualCategory;
import com.probiz.estore.common.model.inventory.Inventory;
import com.probiz.estore.common.model.other.Tag;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.util.SearchUtil;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.StringUtil;
import com.probiz.estore.product.dao.ProductDao;
import com.probiz.estore.product.model.ProductSearchCriteria;

/**
 * Dao implementation for Product.
 */
public class ProductDaoImpl extends HibernateGenericDaoImpl<Product> implements ProductDao {

	private ProductCategoryDao productCategoryDao;
	private VirtualCategoryDao virtualCategoryDao;
	
    public void setProductCategoryDao(ProductCategoryDao productCategoryDao) {
		this.productCategoryDao = productCategoryDao;
	}
    

	public void setVirtualCategoryDao(VirtualCategoryDao virtualCategoryDao) {
		this.virtualCategoryDao = virtualCategoryDao;
	}


	/*
      * (non-Javadoc)
      * @see com.probiz.estore.product.dao.ProductDao#countProductByCategoryId(java.lang.Integer)
      */
    public Integer countProductByCategoryId(Integer categoryId) {
        String hql = "select count(p.productId) from Product p where p.category.categoryId=? and p.status>=0 ";
        Long itemCount = (Long) this.findUnique(hql, categoryId);
        return new Integer(itemCount.toString());
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.product.dao.ProductDao#countProductIncludeAllByCategory(com.probiz.estore.catalog.model.ProductCategory)
      */
    public Integer countProductIncludeAllByCategory(ProductCategory productCategory) {
        String hql = "select count(p.productId) from Product p where p.category.categoryPath like ? and p.status>=0";
        Long itemCount = (Long) this.findUnique(hql, productCategory.getCategoryPath() + "%");
        return new Integer(itemCount.toString());
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.product.dao.ProductDao#countActiveProductIncludeAllByCategory(com.probiz.estore.catalog.model.ProductCategory)
      */
    public Integer countActiveProductIncludeAllByCategory(ProductCategory productCategory) {
        String hql = "select count(p.productId) from Product p where p.status =1 and p.category.categoryPath like ?";
        Long itemCount = (Long) this.findUnique(hql, productCategory.getCategoryPath() + "%");
        return new Integer(itemCount.toString());
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.product.dao.ProductDao#searchByCriteria(com.probiz.estore.product.model.ProductSearchCriteria, com.probiz.estore.core.search.SearchCriteria)
      */
    public List<Product> searchByCriteria(ProductSearchCriteria productSearchCriteria, SearchCriteria searchCriteria) {
    	 //-begin:获得所有符合的标签id
    	Set<Integer> tagIdSet = new HashSet<Integer>();
        if (StringUtils.isNotBlank(productSearchCriteria.getTags())) {
        	String[] tagNameArray = productSearchCriteria.getTags().trim().replaceAll("\\s+",",").split(",");
        	for(int i=0; i< tagNameArray.length; i++){
        		tagIdSet.addAll(this.findByHql("select t.tagId from Tag t where t.tagName like ? and t.module=?", "%"+tagNameArray[i]+"%",Tag.MODULE_PRODUCT));
        	}
        }
        //-end:获得所有符合的标签id
        
        StringBuffer hqlsb = new StringBuffer(100);
        List<Object> paramList = new ArrayList<Object>();
        //start:构建HQL语句
        //特别注意，因为Brand可为空，所以在查询商品品牌名称时候必须加上左外连接。
        hqlsb.append("select p from Product p left join p.brand as b where 1=1 and p.status>=0");
        //-begin:关键词
        if (StringUtils.isNotBlank(productSearchCriteria.getKeywords())) {
            String keywords = SearchUtil.getSqlQueryValue(productSearchCriteria.getKeywords());
            hqlsb.append(" and (");
            hqlsb.append("    p.productName like ? ");
            hqlsb.append(" or p.keywords like ? ");
            hqlsb.append(" or p.productCode like ? ");
            hqlsb.append(" or p.category.categoryName like ? ");
            hqlsb.append(" or p.category.keywords like ? ");
            hqlsb.append(" or b.brandName like ? ");
            hqlsb.append(" )");
            for (int i = 0; i < 6; i++) {
                paramList.add("%" + keywords + "%");
            }
        }
        //-end:关键词
        //-begin:不包含关键词
        if (StringUtils.isNotBlank(productSearchCriteria.getExcludedKeywords())) {
            String excludedKeywords = SearchUtil.getSqlQueryValue(productSearchCriteria.getExcludedKeywords());
            hqlsb.append(" and ");
            hqlsb.append("(p.productName not like ? ");
            hqlsb.append(" and p.keywords not like ? ");
            hqlsb.append(" and p.productCode <> ? )");
            for (int i = 0; i < 2; i++) {
                paramList.add("%" + excludedKeywords + "%");
            }
            paramList.add(excludedKeywords);
        }
        //-end:不包含关键词
        //-start:产品编码
        if (StringUtils.isNotBlank(productSearchCriteria.getProductCode())) {
            hqlsb.append(" and p.productCode = ?");
            paramList.add(productSearchCriteria.getProductCode());
        }
        //-end:产品编码
        //-start:货号
        if (StringUtils.isNotBlank(productSearchCriteria.getProductSkuCode())) {
            hqlsb.append(" and p.productId in (");
            hqlsb.append("select ps.product.productId from ProductSku ps where ps.productSkuCode = ?");
            hqlsb.append(")");
            paramList.add(productSearchCriteria.getProductSkuCode());
        }
        //-end:货号
        //-start:最低价
        if (null != productSearchCriteria.getLowestPrice()) {
            hqlsb.append(" and p.price >= ?");
            paramList.add(productSearchCriteria.getLowestPrice());
        }
        //-end:最低价
        //-start:最高价
        if (null != productSearchCriteria.getHighestPrice()) {
            hqlsb.append(" and p.price <= ?");
            paramList.add(productSearchCriteria.getHighestPrice());
        }
        //-end:最高价
        //-start:类别
        if (StringUtils.isNotBlank(productSearchCriteria.getProductKind())) {
        	hqlsb.append(" and p.productKind = ?");
        	paramList.add(Short.valueOf(productSearchCriteria.getProductKind()));
        }
        //-end:类别
        //-begin:产品目录
        if (!ArrayUtils.isEmpty(productSearchCriteria.getCategoryPaths())) {
            hqlsb.append(" and (");
            for (int i = 0; i < productSearchCriteria.getCategoryPaths().length; i++) {
                hqlsb.append("p.category.categoryPath like ?");
                if (i < productSearchCriteria.getCategoryPaths().length - 1) hqlsb.append(" or ");
                paramList.add(productSearchCriteria.getCategoryPaths()[i] + "%");
            }
            hqlsb.append(" )");
        }
        if (StringUtils.isNotBlank(productSearchCriteria.getCategoryPath())) {
            hqlsb.append(" and (");
            hqlsb.append("p.category.categoryPath like ?");
            hqlsb.append(" )");
            paramList.add(productSearchCriteria.getCategoryPath() + "%");

        }
        if (StringUtils.isNotBlank(productSearchCriteria.getCategoryId())) {
        	hqlsb.append(" and (");
        	hqlsb.append("p.category.categoryId = ?");
        	hqlsb.append(" )");
        	paramList.add(new Integer(productSearchCriteria.getCategoryId()));
        }
        //-end:产品目录
        //-begin:品牌
        if (!ArrayUtils.isEmpty(productSearchCriteria.getBrandIds())) {
        	String brandIdsString = StringUtil.arrayToString(productSearchCriteria.getBrandIds(),",");
        	if(StringUtils.isNotEmpty(brandIdsString)){
	        	 hqlsb.append(" and (");
	        	 hqlsb.append("p.brand.brandId in (").append(brandIdsString).append(")");
	        	 hqlsb.append(" )");
        	}
        }
        //-end:品牌
        //-begin:类型
        if (!ArrayUtils.isEmpty(productSearchCriteria.getProductTypeIds())) {
        	String productTypeIdsString = StringUtil.arrayToString(productSearchCriteria.getProductTypeIds(),",");
        	if(StringUtils.isNotEmpty(productTypeIdsString)){
		    	hqlsb.append(" and (");
		    	hqlsb.append("p.productType.productTypeId in (").append(productTypeIdsString).append(")");
		    	hqlsb.append(" )");
        	}
        }
        //-end:类型
        //-begin:标签名称
        if (StringUtils.isNotBlank(productSearchCriteria.getTags())) {
        	hqlsb.append(" and (");
        	hqlsb.append(" 1=0 ");
        	for(Integer tagId: tagIdSet){
        		hqlsb.append(" or  ','||p.tags||',' like ?");
        		paramList.add("%,"+tagId+",%");
        	}
        	hqlsb.append(" )");
        	
        }
        //-end:标签名称
        //-start:状态
        if (null != productSearchCriteria.getStatus()) {
            hqlsb.append(" and p.status = ?");
            paramList.add(productSearchCriteria.getStatus());
        }
        //-end:状态
        //-start:快速搜索、属性搜索
        if (!ArrayUtils.isEmpty(productSearchCriteria.getAttributeIds())) {
            for (int i = 0; i < productSearchCriteria.getAttributeIds().length; i++) {
                Integer attributeId = Integer.valueOf(productSearchCriteria.getAttributeIds()[i]);
                String attributeValue = productSearchCriteria.getAttributeValues()[i];
                hqlsb.append(" and p.productId in (");
                hqlsb.append("		select pa.product.productId ");
                hqlsb.append("		from ProductAttrValue pa ");
                hqlsb.append("		where pa.attribute.attributeId = ?");
                hqlsb.append("			  and ifnull(pa.shortTextValue, pa.longTextValue) like ?");
                hqlsb.append(") ");
                paramList.add(attributeId);
                paramList.add("%" + attributeValue + "%");
            }
        }
        //-end:快速搜索、属性搜索
        //-start:快速搜索、规格搜索
        if (!ArrayUtils.isEmpty(productSearchCriteria.getOptionValueIds())) {
        	for(int i=0; i< productSearchCriteria.getOptionValueIds().length; i++){
        		hqlsb.append(" and p.productId in(");
        		hqlsb.append("     select ps.product.productId ");
        		hqlsb.append("       from ProductSku ps ");
        		hqlsb.append("       where ps.skuOptionValueInfo like ?");
        		hqlsb.append(")");
        		paramList.add("%:" + productSearchCriteria.getOptionValueIds()[i] + ";%");
        	}
        }
        //-end:快速搜索、规格搜索
        //-begin:库存
        if(null != productSearchCriteria.getIsInventorySearch() && Constants.FLAG_TRUE.equals(productSearchCriteria.getIsInventorySearch())){
        	//是库存方面的搜索
        	hqlsb.append(" and (p.status = 1 or p.status = 0)");
        }
		if(null != productSearchCriteria.getInventoryStatus()){
			if(productSearchCriteria.getInventoryStatus().equals(Inventory.INVENTORY_LACK)){
				hqlsb.append(" and p.productId in(");
				hqlsb.append("     select ps.product.productId ");
        		hqlsb.append("       from ProductSku ps ");
        		hqlsb.append("       where (ps.inventory.quantityOnHand is not null) and (ps.inventory.quantityOnHand - ps.inventory.allocatedQuantity < (case when ps.product.minOrderQuantity is not null then p.minOrderQuantity else 1 end) )");
				hqlsb.append(")");
			}else if(productSearchCriteria.getInventoryStatus().equals(Inventory.INVENTORY_LOW)){
				hqlsb.append(" and p.productId in(");
				hqlsb.append("     select ps.product.productId ");
        		hqlsb.append("       from ProductSku ps ");
        		hqlsb.append("       where (ps.inventory.quantityOnHand is not null) and ( (ps.inventory.quantityOnHand - ps.inventory.allocatedQuantity <= (case when ps.product.minOrderQuantity is not null then ps.product.minOrderQuantity else 1 end))");
        		hqlsb.append("       or  (ps.inventory.quantityOnHand - ps.inventory.allocatedQuantity<=ps.inventory.reorderMinimnm) )");
				hqlsb.append(")");
			}
			hqlsb.append(" and p.status = 1");//只能是已上架商品
		}
		//-end:库存
		//-------------start:虚拟目录----------------
		VirtualCategory virtualCategory =null;
		if(null != productSearchCriteria.getVirtualCategoryId()){
			virtualCategory = virtualCategoryDao.getById(productSearchCriteria.getVirtualCategoryId());
		}else if(StringUtils.isNotBlank(productSearchCriteria.getVirtualCategoryCode())){
			virtualCategory = virtualCategoryDao.getCategoryByCode(productSearchCriteria.getVirtualCategoryCode());
		}
		
		if(null != virtualCategory){
			hqlsb.append(" and ( (1=1");
			if(null != virtualCategory.getFcLowestPrice()){
				hqlsb.append(" and p.price >= ?");
		        paramList.add(virtualCategory.getFcLowestPrice());
			}
			if(null != virtualCategory.getFcHighestPrice()){
				hqlsb.append(" and p.price <= ?");
		        paramList.add(virtualCategory.getFcHighestPrice());
			}
			if(StringUtils.isNotBlank(virtualCategory.getFcKeywords())){
				String keywords = SearchUtil.getSqlQueryValue(virtualCategory.getFcKeywords());
	            hqlsb.append(" and ");
	            hqlsb.append("(p.productName like ? ");
	            hqlsb.append(" or p.keywords like ? ");
	            hqlsb.append(" or p.productCode like ? )");
	            hqlsb.append(" or p.category.categoryName like ? ");
	            hqlsb.append(" or p.category.keywords like ? ");
	            hqlsb.append(" or b.brandName like ? ");
	            for (int i = 0; i < 6; i++) {
	                paramList.add("%" + keywords + "%");
	            }
			}
			if(StringUtils.isNotBlank(virtualCategory.getFcBrands())){
				hqlsb.append(" and p.brand.brandId in (").append(virtualCategory.getFcBrands()).append(")");
			}
			if(StringUtils.isNotBlank(virtualCategory.getFcProductTypes())){
				//注意这里不能用？代替参数方式，否则会报错
				hqlsb.append(" and p.productType.productTypeId in (").append(virtualCategory.getFcProductTypes()).append(")");
			}
			if(StringUtils.isNotBlank(virtualCategory.getFcProductCategories())){
				String[] categoryIds = virtualCategory.getFcProductCategories().split(",");
				if(!ArrayUtils.isEmpty(categoryIds)){
					hqlsb.append(" and (");
					hqlsb.append(" 1=0 ");
					for(int i=0;i<categoryIds.length; i++){
						if(StringUtils.isNotBlank(categoryIds[i])){
							ProductCategory productCategory = productCategoryDao.getById(Integer.valueOf(categoryIds[i]));
							if(null != productCategory){
								hqlsb.append(" or p.category.categoryPath like ?");
								paramList.add(productCategory.getCategoryPath() + "%");
							}
						}
					}
					hqlsb.append(" )");
				}	
				
			}
			if(StringUtils.isNotBlank(virtualCategory.getFcTags())){
				String[] tagIds = virtualCategory.getFcTags().split(",");
				if(!ArrayUtils.isEmpty(tagIds)){
					hqlsb.append(" and (");
					hqlsb.append(" 1=0 ");
					for(int i=0;i<tagIds.length; i++){
						if(StringUtils.isNotBlank(tagIds[i])){
							hqlsb.append(" or ','||p.tags||',' like ?");
							paramList.add("%,"+tagIds[i]+",%");
						}
					}
					hqlsb.append(" )");
				}
	        }
	        //-end:标签名称
			hqlsb.append("  ) or p.productId in(");
			hqlsb.append("    select vpr.product.productId from VirtualcatProdRelation vpr where vpr.virtualCategory.categoryId = ?");
			hqlsb.append("    )");
			hqlsb.append(" )");
			paramList.add(virtualCategory.getCategoryId());
		}
		
		//-------------end:  虚拟目录----------------
        //start:order by
        if (null != productSearchCriteria.getOrderby()) {
            hqlsb.append(" order by ").append(getSortByString(productSearchCriteria.getOrderby()));
        }else{
        	hqlsb.append(" order by p.productId desc");
        }
        //end:order by
        //end:构建HQL语句
        searchCriteria.setHql(hqlsb.toString());
        searchCriteria.removeParamValues();
        for (Object object : paramList) {
            searchCriteria.addParamValue(object);
        }
        List<Product> productList =  searchByCriteria(searchCriteria);
        return productList;
    }

    /**
     * 根据orderby获得 hql语句
     *
     * @param orderby 排序id
     * @return hql语句
     */
    private String getSortByString(short orderby) {
        String orderByString;
        switch (orderby) {
        	case 0: //前台默认
                 orderByString = "p.sortOrder asc,p.shelveTime desc";
                 break;
            case 1:
                orderByString = "p.price asc";
                break;
            case 2:
                orderByString = "p.price desc";
                break;
            case 3:
                orderByString = "convert_gbk(p.productName) asc";
                break;
            case 4:
                orderByString = "convert_gbk(p.productName) desc";
                break;
            case 5:
                orderByString = "p.shelveTime asc";
                break;
            case 6:
                orderByString = "p.shelveTime desc";
                break;    
            case 7:
                orderByString = "p.updateTime asc";
                break;
            case 8:
                orderByString = "p.updateTime desc";
                break;
            case 9:
                orderByString = "p.productStat.buyCount asc";
                break;
            case 10:
                orderByString = "p.productStat.buyCount desc";
                break;
            case 11:
            	orderByString = "p.productStat.buyTimes asc";
            	break;
            case 12:
            	orderByString = "p.productStat.buyTimes desc";
            	break;
            case 13:
            	orderByString = "p.productStat.viewCount asc";
            	break;
            case 14:
            	orderByString = "p.productStat.viewCount desc";
            	break;
            case 15:
                orderByString = "p.productStat.reviewScore asc";
                break;
            case 16:
                orderByString = "p.productStat.reviewScore desc";
                break;
            case 17:
            	orderByString = "p.productStat.reviewCount asc";
            	break;
            case 18:
            	orderByString = "p.productStat.reviewCount desc";
            	break;
            case 19: 
            	orderByString = "convert_gbk(p.productType.productTypeName) asc";
            	break;
            case 20:
            	orderByString = "convert_gbk(p.productType.productTypeName) desc";
            	break;
            case 21: 
            	orderByString = "convert_gbk(p.category.categoryName) asc";
            	break;
            case 22:
            	orderByString = "convert_gbk(p.category.categoryName) desc";
            	break;
            case 23: 
            	orderByString = "convert_gbk(p.brand.brandName) asc";
            	break;
            case 24:
            	orderByString = "convert_gbk(p.brand.brandName) desc";
            	break;
            case 25: 
            	orderByString = "p.status desc";
            	break;
            case 26:
            	orderByString = "p.status asc";
            	break;
            default:
                orderByString = "p.productId desc";
                break;
        }
        return orderByString;
    }


   
    /*
      * (non-Javadoc)
      * @see com.probiz.estore.product.dao.ProductDao#getNumOfProductsByStoreId(java.lang.Integer)
      */
    public Long[] getNumOfProductsByStoreId(Integer storeId) {
        Long activeItemCount = (Long) this.findUnique("select count(p.productId) from Product p where p.status = 1 and p.sellerStore.sellerStoreId = " + storeId);
        Long itemCount = (Long) this.findUnique("select count(p.productId) from Product p where p.status>=0 and p.sellerStore.sellerStoreId = " + storeId);
        return new Long[]{activeItemCount, itemCount};

    }


    /*
      * (non-Javadoc)
      * @see com.probiz.estore.product.dao.ProductDao#getMaxPriceByCategoryId(java.lang.String)
      */
    public BigDecimal getMaxPriceByCategoryId(String fullCategoryPath) {
        return (BigDecimal) this.findUnique("select max(p.lowestPrice) from Product p where p.status = 1 and p.category.categoryPath like ?", fullCategoryPath + "%");
    }

    /*
      * (non-Javadoc)
      * @see com.probiz.estore.product.dao.ProductDao#getProductsByCategoryAndDisplayFlag(com.probiz.estore.catalog.model.ProductCategory, java.lang.Short, int)
      */
    public List<Product> getProductsByCategoryAndDisplayFlag(final ProductCategory productCategory, final Short displayFlag, final int size) {
        List list;
        list = getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                StringBuffer sb = new StringBuffer();
                sb.append("from Product p where p.status = ").append(
                        Product.STATUS_ACTIVE);
                sb.append(" and p.category.categoryPath like :fullCategoryPath ");
                sb.append(" and p.displayFlag like :displayFlag");
                Query query = session.createQuery(sb.toString());
                query.setString("fullCategoryPath", productCategory.getCategoryPath() + "%");
                query.setString("displayFlag", "%" + displayFlag.toString() + ",%");
                query.setMaxResults(size);
                return (List<Product>) query.list();
            }

        });
        return list;
    }
    
   /*
    * (non-Javadoc)
    * @see com.probiz.estore.product.dao.ProductDao#getProductByProductCodeNotByProductId(java.lang.String, java.lang.Integer)
    */
    public Long getSizeByProductCodeByNotProductId(final String productCode,final Integer productId){
    	Long size;
    	if(productId != null){
    		
    		size = (Long)getHibernateTemplate().executeWithNewSession(new HibernateCallback() {
    			public Object doInHibernate(Session session)
    					throws HibernateException, SQLException {
    				StringBuffer sb = new StringBuffer();
    				sb.append("select count(*) from Product p where p.productCode = ? and p.productId != ?");
    				Query query = session.createQuery(sb.toString());
    				query.setString(0, productCode);
    				query.setInteger(1, productId);
    				Long rows =  (Long)query.uniqueResult();
    				return rows;
    			}

    		});
    	}else{
    		size = (Long)getHibernateTemplate().executeWithNewSession(new HibernateCallback() {
    			public Object doInHibernate(Session session)
    					throws HibernateException, SQLException {
    				StringBuffer sb = new StringBuffer();
    				sb.append("select count(*) from Product p where p.productCode = ? ");
    				Query query = session.createQuery(sb.toString());
    				query.setString(0, productCode);
    				Long rows =  (Long)query.uniqueResult();
    				return rows;
    			}

    		});
    	}	
    	return size;
    	
    }
    
    /*
     * (non-Javadoc)
     * @see com.probiz.estore.product.dao.ProductDao#getRandomProductList(int)
     */
    public List<Product> getRandomProductList(final int count){
    	List list;
		list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery("from Product p where p.status = 1 order by rand()");
				query.setMaxResults(count);
				List<Product> rows = (List<Product>) query.list();
				return rows;
			}

		});
		return list;

    }
    /*
     * (non-Javadoc)
     * @see com.probiz.estore.product.dao.ProductDao#countProductTotal()
     */
    public Long countProductTotal(){
    	return this.countByHql("from Product p where p.status>=0");
    }
    /*
     * (non-Javadoc)
     * @see com.probiz.estore.product.dao.ProductDao#countShelvedProductTotal()
     */
    public Long countShelvedProductTotal(){
    	return this.countByHql("from Product p where p.status = 1");
    }
 
    /**
	 * 根据fieldName改变产品统计对应field的值。count为改变数量，可以为正，也可以为负。
	 */
	public void updateStatField(final Integer productStatId,final String fieldName,final Integer count) {
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				StringBuffer sb = new StringBuffer();
				sb.append("update product_stat set ").append(fieldName).append(" = ").append(fieldName);
				if(count>=0){
					sb.append(" + ").append(count);
				}else{
					sb.append(" - ").append(count);
				}
				sb.append(" where productStatId=").append(productStatId);
				int i=session.createSQLQuery(sb.toString()).executeUpdate();
				return i;
			}

		});
	}
	
	public List<Product> getListByDelete(){
		String hql = "from Product p where p.status >= 0";
		return this.findByHql(hql);
	}
}
